namespace RBAC.Read.Api.Application.Handler.ERP.OutboundManagement
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.Dto.Output;
    using RBAC.Domain.OutboundManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.ERP.OutboundManagement;
    using RBAC.Read.Api.Application.Dto.ERP;

    /// <summary>
    /// 销售出库分页 处理器
    /// </summary>
    public class GetSalesOutboundPageHandler : IRequestHandler<GetSalesOutboundPageCommand, APIPaging<SalesOutboundListDto>>
    {
        private readonly IBaseRepository<SalesOutbound> repository;
        private readonly ILogger<GetSalesOutboundPageHandler> logger;

        public GetSalesOutboundPageHandler(
            IBaseRepository<SalesOutbound> repository,
            ILogger<GetSalesOutboundPageHandler> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        public Task<APIPaging<SalesOutboundListDto>> Handle(GetSalesOutboundPageCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<SalesOutboundListDto>();
            try
            {
                logger.LogInformation("开始获取销售出库分页 PageIndex={PageIndex}, PageSize={PageSize}", request.PageIndex, request.PageSize);

                // 若指定了某年某月，折算为起止日期（当未显式传入Start/End时）
                if (request.Year.HasValue && request.Month.HasValue)
                {
                    var y = request.Year.Value;
                    var m = request.Month.Value;
                    if (m >= 1 && m <= 12)
                    {
                        var first = new DateTime(y, m, 1);
                        var last = first.AddMonths(1).AddDays(-1);
                        request.StartDate ??= first;
                        request.EndDate ??= last;
                    }
                }

                var where = BuildWhereClause(request);
                var parameters = BuildParameters(request);

                var (data, total) = repository.GetPaged(request.PageIndex, request.PageSize, where, request.OrderBy, parameters);

                var list = data.Select(o => new SalesOutboundListDto
                {
                    Id = o.Id,
                    OrderCode = o.OrderCode,
                    OrderDate = o.OrderDate,
                    CustomerCode = o.CustomerCode,
                    CustomerName = o.CustomerName,
                    OrderStatus = o.OrderStatus,
                    BusinessStatus = o.BusinessStatus,
                    Warehouse = o.Warehouse,
                    DeliveryNo = o.DeliveryNo,
                    DeliveryType = o.DeliveryType,
                    Remark = o.Remark
                }).ToList();

                result.Code = APIEnums.Success;
                result.PageDatas = list;
                result.TotalCount = total;
                result.Msg = "获取销售出库分页成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取销售出库分页失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取销售出库分页失败";
                result.PageDatas = new List<SalesOutboundListDto>();
                result.TotalCount = 0;
            }

            return Task.FromResult(result);
        }

        private string BuildWhereClause(GetSalesOutboundPageCommand request)
        {
            var conditions = new List<string>();
            if (!string.IsNullOrWhiteSpace(request.OrderCode))
            {
                conditions.Add("OrderCode LIKE @OrderCode");
            }
            if (request.StartDate.HasValue)
            {
                conditions.Add("OrderDate >= @StartDate");
            }
            if (request.EndDate.HasValue)
            {
                // 包含当天：若列为日期时间，此条件即可
                conditions.Add("OrderDate <= @EndDate");
            }
            if (!string.IsNullOrWhiteSpace(request.OrderStatus))
            {
                conditions.Add("OrderStatus = @OrderStatus");
            }
            if (!string.IsNullOrWhiteSpace(request.BusinessStatus))
            {
                conditions.Add("BusinessStatus = @BusinessStatus");
            }
            if (!string.IsNullOrWhiteSpace(request.Warehouse))
            {
                conditions.Add("Warehouse = @Warehouse");
            }

            return conditions.Count > 0 ? string.Join(" AND ", conditions) : string.Empty;
        }

        private object BuildParameters(GetSalesOutboundPageCommand request)
        {
            var p = new Dictionary<string, object>();
            if (!string.IsNullOrWhiteSpace(request.OrderCode))
            {
                p["OrderCode"] = $"%{request.OrderCode}%";
            }
            if (request.StartDate.HasValue)
            {
                p["StartDate"] = request.StartDate.Value.Date;
            }
            if (request.EndDate.HasValue)
            {
                // 若 EndDate 仅为日期，包含当天，可设置为当天23:59:59
                var end = request.EndDate.Value;
                if (end.TimeOfDay == TimeSpan.Zero)
                {
                    end = end.Date.AddDays(1).AddTicks(-1);
                }
                p["EndDate"] = end;
            }
            if (!string.IsNullOrWhiteSpace(request.OrderStatus))
            {
                p["OrderStatus"] = request.OrderStatus;
            }
            if (!string.IsNullOrWhiteSpace(request.BusinessStatus))
            {
                p["BusinessStatus"] = request.BusinessStatus;
            }
            if (!string.IsNullOrWhiteSpace(request.Warehouse))
            {
                p["Warehouse"] = request.Warehouse;
            }
            return p;
        }
    }
}
